<template>
  <div class="">
    <div class="ls-card m-t-16 p-20">
      <el-form :rules="rules" ref="form" :model="form" label-width="120px" size="small">
        <!-- 当前密码 -->
        <el-form-item label="当前密码" prop="origin_password">
          <el-input class="ls-input" v-model="form.origin_password" placeholder="请输入当前密码">
          </el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="password_confirm">
          <el-input class="ls-input" v-model="form.password_confirm" placeholder="请输入新密码">
          </el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="password">
          <el-input class="ls-input" v-model="form.password" placeholder="请确认新密码">
          </el-input>
        </el-form-item>
      </el-form>
    </div>

    <!-- 底部保存或取消 -->
    <div class="bg-white ls-fixed-footer">
      <div class="row-center flex" style="height: 100%;">
        <el-button size="small" @click="$router.go(-1)">取消</el-button>
        <el-button size="small" type="primary" @click="onSubmit('form')">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator'
import { apiResetPassword } from '@/api/setting'
import { apiLogout } from '@/api/app'


@Component
export default class ListsDetail extends Vue {
  /** S Data **/

  // 添加商城表单数据
  form: any = {
    origin_password: '', // 原密码
    password_confirm: '', // 新密码
    password: '' // 确认密码
  };

  // 表单校验
  rules = {
    origin_password: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
    password_confirm: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      {
        validator: (rule: object, value: string, callback: any) => {
          !value
            ? callback(new Error('请输入密码'))
            : callback()
        },
        trigger: 'blur'
      }
    ],
    password: [
      { required: true, message: '请再次输入密码', trigger: 'blur' },
      {
        validator: (rule: object, value: string, callback: any) => {
          if (this.form.password_confirm) {
            if (!value) callback(new Error('请再次输入密码'))
            if (value !== this.form.password_confirm) callback(new Error('两次输入密码不一致!'))
          }
          callback()
        },
        trigger: 'blur'
      }
    ]
  };

  /** E Data **/

  /** S Methods **/
  // 点击表单提交
  onSubmit (formName: string) {
    // 验证表单格式是否正确
    const refs = this.$refs[formName] as HTMLFormElement
    refs.validate((valid: boolean): any => {
      if (!valid) return
      this.handleEdit()
    })
  }

  async handleEdit () {
    await apiResetPassword({ ...this.form })
    this.logout()
  }

  logout () {
    apiLogout().then(() => {
      this.$store.commit('setUserInfo', {})
      this.$store.commit('setPermission', {})
      this.$router.push('/account/login')
    })
  }
  /** E Methods **/
}
</script>

<style lang="scss" scoped>
.ls-input {
  width: 380px;
}
</style>
